<script setup lang="tsx">
import { directAxios } from "@/axios/index";
import { reactive, ref, watch, onMounted, unref, defineProps } from "vue";
import { Form, FormSchema } from "@/components/Form";
import { ElCheckbox, ElMessage } from "element-plus";
import { useForm } from "@/hooks/web/useForm";
import { usePermissionStore } from "@/store/modules/permission";
import { useRouter } from "vue-router";
import type { RouteLocationNormalizedLoaded } from "vue-router";
import { UserType } from "@/api/login/types";
import { useValidator } from "@/hooks/web/useValidator";
import { useUserStore } from "@/store/modules/user";
import { BaseButton } from "@/components/Button";
import { Icon } from "@/components/Icon";

// 定义props接收父组件的方法
const props = defineProps<{
  loadingMethods?: {
    startPageLoading: () => void;
    endPageLoading: () => void;
  };
}>();

const { required } = useValidator();

const emit = defineEmits(["to-register"]);

const userStore = useUserStore();
const permissionStore = usePermissionStore();

const { currentRoute, push } = useRouter();

const rules = {
  loginCode: [required()],
};

const schema = reactive<FormSchema[]>([
  {
    field: "title",
    colProps: {
      span: 24,
    },
    formItemProps: {
      slots: {
        default: () => {
          return <h2 class="f-s30 font-bold text-center w-[100%]">登录</h2>;
        },
      },
    },
  },
  {
    field: "loginCode",
    label: "",
    component: "Input",
    colProps: {
      span: 24,
    },
    componentProps: {
      placeholder: "输入登录码",
      prefixIcon: <Icon icon="svg-icon:user" />,
    },
  },

  {
    field: "tool",
    colProps: {
      span: 24,
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="flex justify-between items-center w-[100%]">
                <ElCheckbox
                  v-model={remember.value}
                  label="记住我"
                  size="small"
                />
              </div>
            </>
          );
        },
      },
    },
  },
  {
    field: "login",
    colProps: {
      span: 24,
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="w-[100%]">
                <BaseButton
                  loading={loading.value}
                  type="primary"
                  class="w-[100%]"
                  onClick={signIn}
                >
                  登录
                </BaseButton>
              </div>
            </>
          );
        },
      },
    },
  },
 {
     field: "updatePackage",
    colProps: {
      span: 24,
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
          <>
            <div style="line-height: 20px;font-size:12px;color:var(--el-color-primary);font-weight: 500;display: flex;justify-content: flex-end;width: 100%;">
              <el-upload
                ref={uploadRef}
                auto-upload={false}
                show-file-list={false}

                onChange={handleFileChange}

              >
              {/*  accept=".xlsx,.xls" */}
                 {/* beforeUpload={beforeUpload} */}
                {{
                  default: () => (

                    <div

                     type="text"
                      size="small"

                      loading={uploadLoading.value}
                    >
                      {uploadLoading.value ? '上传中...' : '导入更新包'}
                    </div>
                  )
                }}
              </el-upload>
            </div>
          </>
          );
        },
      },
    },
  },
]);

const remember = ref(userStore.getRememberMe);
const uploadRef = ref<UploadInstance>();
const uploadLoading = ref(false);
const selectedFile = ref<File | null>(null);
const initLoginInfo = () => {
  const loginInfo = userStore.getLoginInfo;
  if (loginInfo) {
    const { loginCode } = loginInfo;
    setValues({ loginCode });
  }
};
onMounted(() => {
  initLoginInfo();
});

const { formRegister, formMethods } = useForm();
const { getFormData, getElFormExpose, setValues } = formMethods;

const loading = ref(false);

const redirect = ref<string>("");

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string;
  },
  {
    immediate: true,
  }
);

// 开始页面跳转loading
const startPageLoading = () => {
  if (props.loadingMethods?.startPageLoading) {
    props.loadingMethods.startPageLoading();
  } else {
    console.warn("父组件的loadingMethods未提供");
  }
}

// 结束页面跳转loading
const endPageLoading = () => {
  if (props.loadingMethods?.endPageLoading) {
    props.loadingMethods.endPageLoading();
  } else {
    console.warn("父组件的loadingMethods未提供");
  }
}
// 文件选择变化处理
const handleFileChange = (file: UploadFile, fileList: UploadFiles) => {
  selectedFile.value = file.raw as File;
  // 自动触发上传
  if (selectedFile.value) {
    updatePackage();
  }
}

// 文件上传前验证
const beforeUpload = (file: File) => {
  if (!file.raw) {
    ElMessage.error("文件不存在");
    return false;
  }

  // 检查文件扩展名
  const fileExtension = file.name.split(".").pop()?.toLowerCase();
  const allowedExtensions = ["xls", "xlsx"];

  if (!fileExtension || !allowedExtensions.includes(fileExtension)) {
    ElMessage.error("文件格式错误！只能上传 .xlsx 或 .xls 格式的Excel文件");
    return false;
  }

  // 检查MIME类型（可选，因为不同浏览器可能识别不同）
  const allowedMimeTypes = [
    "application/vnd.ms-excel",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "application/vnd.ms-excel.sheet.macroEnabled.12",
    "application/octet-stream", // 某些情况下可能是这个类型
  ];

  // 如果MIME类型不为空且不在允许列表中，给出警告但继续（因为扩展名正确）
  if (file.raw.type && !allowedMimeTypes.includes(file.raw.type)) {
    console.warn("文件MIME类型不匹配，但扩展名正确，继续处理");
  }

  // 限制文件大小（10MB）
  // const maxSize = 10 * 1024 * 1024; // 10MB
  // if (file.size && file.size > maxSize) {
  //   ElMessage.error('文件大小不能超过 10MB');
  //   return false;
  // }

  return true;
}

// 导入更新包
const updatePackage = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择文件');
    return;
  }

  try {
    // 确认对话框
    await ElMessageBox.confirm(
      '确定要导入更新包吗？此操作可能会影响系统功能。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    uploadLoading.value = true;

    const formData = new FormData();
    formData.append('file', selectedFile.value);



const res = await "/api/import/importDataUpdatePackage".post(formData, {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          });
    if (res.code === 200) {
      ElMessage.success('更新包导入成功！');

      // // 根据返回结果处理后续逻辑
      // if (res.data?.needRestart) {
      //   ElMessageBox.confirm(
      //     '更新包已成功导入，系统需要重启以应用更新。是否立即重启？',
      //     '系统重启提示',
      //     {
      //       confirmButtonText: '立即重启',
      //       cancelButtonText: '稍后重启',
      //       type: 'warning',
      //     }
      //   ).then(() => {
      //     // 执行重启逻辑
      //     window.location.reload();
      //   });
      // }
    } else {
      ElMessage.error(res.msg || '更新包导入失败');
    }
  } catch (error: any) {
    console.error('导入更新包失败:', error);

    // if (error?.response?.status === 413) {
    //   ElMessage.error('文件太大，请选择小于100MB的文件');
    // } else if (error?.code === 'ECONNABORTED') {
    //   ElMessage.error('上传超时，请稍后重试');
    // } else if (error !== 'cancel') {
    //   ElMessage.error(error?.msg || '导入更新包失败，请重试');
    // }
  } finally {
    uploadLoading.value = false;
    // 清空已选文件
    selectedFile.value = null;
    if (uploadRef.value) {
      uploadRef.value.clearFiles();
    }
  }
}
// 登录
const signIn = async () => {
  const formRef = await getElFormExpose();
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true;
      const formData = await getFormData<UserType>();
      console.log(formData);
      try {
        const params = {
          loginCode: formData.loginCode,
        };

        const res = await directAxios.post(
          "/api/login/validate",
          params,
          {
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
            },
            transformRequest: [(data) => data.toString()],
          }
        );
        if (res.code === 200) {
          if (res) {
            // 是否记住我
            if (unref(remember)) {
              userStore.setLoginInfo({
                loginCode: formData.loginCode,
              });
            } else {
              userStore.setLoginInfo(undefined);
            }
            userStore.setRememberMe(unref(remember));
            userStore.setUserInfo(res.data);

            // 开始页面跳转loading
            // startPageLoading();

            // 生成静态路由
            await permissionStore.generateRoutes("static").catch(() => {});

            // 直接跳转到首页或指定页面
            const targetPath = redirect.value || "/";
            await push({ path: targetPath });

            // 跳转完成后结束loading
            // setTimeout(() => {
            //   endPageLoading();
            // }, 500);
          }
        } else {
          ElMessage.error(res.data.msg);
        }
      } catch (error) {
        // 出错时也要结束loading
        endPageLoading();
        ElMessage.error('登录失败，请重试');
      } finally {
        loading.value = false;
      }
    }
  });
};
</script>

<template>
  <Form
    :schema="schema"
    :rules="rules"
    label-position="top"
    hide-required-asterisk
    size="large"
    class="logon-form dark:(border-1 border-[var(--el-border-color)] border-solid)"
    @register="formRegister"
  />
</template>
